﻿using SwParaPlatform2.logger;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace SwParaPlatform2.tools
{
    internal class DirectoryHelper
    {
        public static void ForceDeleteDirectory(string folderPath)
        {
            if (!Directory.Exists(folderPath))
            {
                Logger.Instance.Log("❗文件夹不存在：" + folderPath);
                return;
            }

            try
            {
                Directory.Delete(folderPath, true);
                Logger.Instance.Log("✅ 文件夹直接删除成功：" + folderPath);
            }
            catch (IOException)
            {
                Logger.Instance.Log("⚠️ 文件被占用，尝试强制解除...");
                KillProcessesLockingFolder(folderPath);

                // 再次尝试删除
                Directory.Delete(folderPath, true);
                Logger.Instance.Log("✅ 释放后删除成功：" + folderPath);
            }
            catch (UnauthorizedAccessException)
            {
                //Logger.Instance.Log("⚠️ 没有权限，尝试强制解除...");
                //KillProcessesLockingFolder(folderPath);

                //Directory.Delete(folderPath, true);
                //Logger.Instance.Log("✅ 释放后删除成功：" + folderPath);
            }
        }

        private static string GetDLLPath()
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            string assemblyLocation = assembly.Location;
            string directoryPath = Path.GetDirectoryName(assemblyLocation);
            return directoryPath;
        }

        private static void KillProcessesLockingFolder(string folderPath)
        {
            string handleExe = Path.Combine(GetDLLPath(), "handle.exe");

            if (!File.Exists(handleExe))
            {
                throw new FileNotFoundException($"找不到 handle.exe，请确认放置路径{handleExe}正确。");
            }

            ProcessStartInfo psi = new ProcessStartInfo
            {
                FileName = handleExe,
                Arguments = $"-accepteula \"{folderPath}\"",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            };

            Process proc = Process.Start(psi);
            string output = proc.StandardOutput.ReadToEnd();
            proc.WaitForExit();

            // 用正则匹配占用该文件的PID
            Regex regex = new Regex(@"\spid: (\d+)");
            MatchCollection matches = regex.Matches(output);

            foreach (Match match in matches)
            {
                int pid;
                if (int.TryParse(match.Groups[1].Value, out pid))
                {
                    try
                    {
                        Process.GetProcessById(pid).Kill();
                        Logger.Instance.Log($"🔪 杀掉占用进程 PID = {pid}");
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Log($"⚠️ 无法杀掉进程 PID = {pid}，原因：" + ex.Message);
                    }
                }
            }
        }
    }
}
